import React, { useMemo, useRef, useState } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import { Layout, UI, useThemeColors, PickerService } from '@gaozh1024/rn-toolkit';
import { openPicker, openPickerControlled } from '@gaozh1024/rn-toolkit';
import type { PickerItem } from '@gaozh1024/rn-toolkit/lib/components/feedback/Picker/PickerService';

type Direction = 'bottom' | 'top' | 'left' | 'right' | 'fade' | 'none' | 'ios';

const fruitCol: PickerItem[] = [
    { label: '苹果', value: 'apple' },
    { label: '香蕉', value: 'banana' },
    { label: '橙子', value: 'orange' },
    { label: '葡萄', value: 'grape' },
    { label: '桃子', value: 'peach' },
];

const provinces = ['广东', '浙江', '四川'] as const;
const citiesMap: Record<typeof provinces[number], PickerItem[]> = {
    广东: [
        { label: '广州', value: 'gz' },
        { label: '深圳', value: 'sz' },
        { label: '佛山', value: 'fs' },
    ],
    浙江: [
        { label: '杭州', value: 'hz' },
        { label: '宁波', value: 'nb' },
        { label: '温州', value: 'wz' },
    ],
    四川: [
        { label: '成都', value: 'cd' },
        { label: '绵阳', value: 'my' },
        { label: '德阳', value: 'dy' },
    ],
};

const makeYearMonthDay = () => {
    const years: PickerItem[] = [2024, 2025, 2026].map(y => ({ label: `${y}年`, value: y }));
    const months: PickerItem[] = Array.from({ length: 12 }, (_, i) => ({ label: `${i + 1}月`, value: i + 1 }));
    const days31: PickerItem[] = Array.from({ length: 31 }, (_, i) => ({ label: `${i + 1}日`, value: i + 1 }));
    return { years, months, days31 };
};

const PickerTestScreen: React.FC = () => {
    const colors = useThemeColors();

    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
    });

    // 行为与样式配置
    const [title, setTitle] = useState<string>('请选择');
    const [direction, setDirection] = useState<Direction>('bottom');
    const [initialIndicesStr, setInitialIndicesStr] = useState<string>('0,0');
    const [initialValuesStr, setInitialValuesStr] = useState<string>('');

    // 数据集合（示例）
    const [columns, setColumns] = useState<PickerItem[][]>([
        fruitCol,
    ]);
    const [useMultiCols, setUseMultiCols] = useState<boolean>(false);
    const [useThreeCols, setUseThreeCols] = useState<boolean>(false);

    // 交互结果
    const [lastValues, setLastValues] = useState<any[]>([]);
    const [cancelCount, setCancelCount] = useState<number>(0);
    const [openCount, setOpenCount] = useState<number>(0);

    // 受控引用
    const [ctrlId, setCtrlId] = useState<string | null>(null);
    const ctrlUpdateRef = useRef<((cols: PickerItem[][]) => void) | null>(null);
    const ctrlCloseRef = useRef<(() => void) | null>(null);

    const parseInitialIndices = useMemo(() => {
        const arr = initialIndicesStr
            .split(',')
            .map(s => parseInt(s.trim()))
            .filter(n => Number.isFinite(n));
        return arr.length ? arr : undefined;
    }, [initialIndicesStr]);

    // 示例数据切换
    const useSingleColumn = () => {
        setUseMultiCols(false);
        setUseThreeCols(false);
        setColumns([fruitCol]);
    };

    const useProvinceCity = () => {
        setUseMultiCols(true);
        setUseThreeCols(false);
        setColumns([
            provinces.map(p => ({ label: p, value: p })),
            citiesMap['广东'],
        ]);
        setInitialIndicesStr('0,0');
    };

    const useYearMonthDay = () => {
        setUseMultiCols(false);
        setUseThreeCols(true);
        const { years, months, days31 } = makeYearMonthDay();
        setColumns([years, months, days31]);
        setInitialIndicesStr('0,0,0');
    };

    const parseInitialValues = useMemo(() => {
        const arr = initialValuesStr
            .split(',')
            .map(s => s.trim())
            .filter(s => s.length > 0);
        return arr;
    }, [initialValuesStr]);

    const valuesToIndices = (cols: PickerItem[][], values: any[]): number[] | undefined => {
        if (!values || !values.length) return undefined;
        const res: number[] = [];
        for (let i = 0; i < values.length && i < cols.length; i++) {
            const idx = cols[i].findIndex(item => item.value === values[i]);
            const maxIdx = Math.max((cols[i]?.length ?? 0) - 1, 0);
            res.push(Math.min(Math.max(idx >= 0 ? idx : 0, 0), maxIdx));
        }
        return res.length ? res : undefined;
    };

    const initialIndicesComputed = useMemo(() => {
        const byValues = valuesToIndices(columns, parseInitialValues);
        return byValues ?? parseInitialIndices;
    }, [columns, parseInitialValues, parseInitialIndices]);

    // 基础用法
    const openBasic = async () => {
        try {
            setOpenCount(n => n + 1);
            const vals = await openPicker({
                columns,
                initialIndices: initialIndicesComputed,
                title,
                direction,
            });
            setLastValues(vals);
        } catch (e) {
            if (String(e) === 'cancel') {
                setCancelCount(n => n + 1);
            }
        }
    };

    const ctrlUpdateSelectionRef = useRef<((inds: number[]) => void) | null>(null);

    const setSelectionByValues = () => {
        if (!ctrlUpdateSelectionRef.current) return;
        const inds = valuesToIndices(columns, parseInitialValues || []);
        if (inds && inds.length) ctrlUpdateSelectionRef.current(inds);
    };

    const setSelectionProvinceCity = (prov: typeof provinces[number], cityValue: string) => {
        if (!ctrlUpdateSelectionRef.current) return;
        const vals = [prov, cityValue];
        const inds = valuesToIndices([
            provinces.map(p => ({ label: p, value: p })),
            citiesMap[prov],
        ], vals);
        if (inds) ctrlUpdateSelectionRef.current(inds);
    };

    const setSelectionYMD = (y: number, m: number, d: number) => {
        if (!ctrlUpdateSelectionRef.current) return;
        const { years, months } = makeYearMonthDay();
        const days: PickerItem[] = Array.from({ length: 31 }, (_, i) => ({ label: `${i + 1}日`, value: i + 1 }));
        const inds = valuesToIndices([years, months, days], [y, m, d]);
        if (inds) ctrlUpdateSelectionRef.current(inds);
    };

    // 受控用法：打开
    const openControlled = () => {
        const ctrl = openPickerControlled({
            columns,
            initialIndices: parseInitialIndices,
            title,
            direction,
        });
        setCtrlId(ctrl.id);
        ctrlUpdateRef.current = ctrl.updateColumns;
        ctrlCloseRef.current = ctrl.close;
        setOpenCount(n => n + 1);

        ctrl.result
            .then(vals => setLastValues(vals))
            .catch(e => {
                if (String(e) === 'cancel') setCancelCount(n => n + 1);
            })
            .finally(() => {
                setCtrlId(null);
                ctrlUpdateRef.current = null;
                ctrlCloseRef.current = null;
            });
    };

    // 受控用法：动态更新列（模拟联动）
    const updateSecondColTo = (prov: typeof provinces[number]) => {
        if (!ctrlUpdateRef.current) return;
        ctrlUpdateRef.current([
            provinces.map(p => ({ label: p, value: p })),
            citiesMap[prov],
        ]);
    };

    const updateDaysTo = (count: number) => {
        if (!ctrlUpdateRef.current) return;
        const { years, months } = makeYearMonthDay();
        const days: PickerItem[] = Array.from({ length: count }, (_, i) => ({ label: `${i + 1}日`, value: i + 1 }));
        ctrlUpdateRef.current([years, months, days]);
    };

    const closeControlled = () => {
        ctrlCloseRef.current?.();
    };

    // 长文案示例
    const useLongLabels = () => {
        setUseMultiCols(false);
        setUseThreeCols(false);
        setColumns([
            [
                { label: '这是一个非常非常长的选项示例文本A', value: 'A' },
                { label: '这是一个非常非常长的选项示例文本B', value: 'B' },
                { label: '这是一个非常非常长的选项示例文本C', value: 'C' },
            ],
        ]);
        setInitialIndicesStr('0');
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'Picker 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="PickerTestScreen"
        >
            {/* 行为与样式 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>行为与样式</UI.Text>
                    <View style={styles.col}>
                        <UI.Text children={'标题（title）'} />
                        <UI.Input
                            value={title}
                            onChangeText={setTitle}
                            placeholder="请选择"
                            testID="input-title"
                        />
                        <UI.Text children={'初始索引（initialIndices，逗号分隔）'} />
                        <UI.Input
                            value={initialIndicesStr}
                            onChangeText={setInitialIndicesStr}
                            placeholder="0,0"
                            keyboardType="numbers-and-punctuation"
                            testID="input-initial-indices"
                        />
                        <UI.Text children={'默认选中值（逗号分隔）'} />
                        <UI.Input
                            value={initialValuesStr}
                            onChangeText={setInitialValuesStr}
                            placeholder="apple, sz 或 2025, 6, 30"
                            testID="input-initial-values"
                        />
                    </View>
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button
                            title="方向：bottom"
                            variant={direction === 'bottom' ? 'primary' : 'outline'}
                            onPress={() => setDirection('bottom')}
                            testID="btn-direction-bottom"
                        />
                        <UI.Button
                            title="方向：none"
                            variant={direction === 'none' ? 'primary' : 'outline'}
                            onPress={() => setDirection('none')}
                            testID="btn-direction-none"
                        />
                        <UI.Button
                            title="方向：ios"
                            variant={direction === 'ios' ? 'primary' : 'outline'}
                            onPress={() => setDirection('ios')}
                            testID="btn-direction-ios"
                        />
                    </View>
                </Layout.Card>
            </View>

            {/* 数据集选择 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>数据集选择</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="单列：水果" variant={!useMultiCols && !useThreeCols ? 'primary' : 'outline'} onPress={useSingleColumn} fullWidth testID="btn-dataset-fruit" />
                        <UI.Button title="两列：省/市" variant={useMultiCols ? 'primary' : 'outline'} onPress={useProvinceCity} fullWidth testID="btn-dataset-province-city" />
                        <UI.Button title="三列：年/月/日" variant={useThreeCols ? 'primary' : 'outline'} onPress={useYearMonthDay} fullWidth testID="btn-dataset-ymd" />
                        <UI.Button title="单列：长文案" variant="outline" onPress={useLongLabels} fullWidth testID="btn-dataset-long" />
                    </View>
                </Layout.Card>
            </View>

            {/* 基础用法 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>基础用法（openPicker）</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="打开 Picker" onPress={openBasic} fullWidth testID="btn-open-basic" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>交互结果：</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-last-values">最后选择值：{String(lastValues.join(', '))}</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-open-count">打开次数：{openCount}</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-cancel-count">取消次数：{cancelCount}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* 受控用法：动态更新与关闭 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>受控用法（openPickerControlled）</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="打开（受控）" onPress={openControlled} fullWidth testID="btn-open-controlled" />
                        <UI.Button title="关闭（受控）" variant="outline" onPress={closeControlled} fullWidth testID="btn-close-controlled" />
                    </View>

                    {/* 按值设置选中（受控） */}
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button title="设置选中（按默认值）" variant="outline" onPress={setSelectionByValues} fullWidth testID="btn-set-selection-from-values" />
                    </View>

                    {/* 两列联动：更新第二列 & 按值设置选中 */}
                    {useMultiCols && (
                        <View style={[styles.row, { marginTop: 12 }]}>
                            <UI.Button title="更新二列：广东" variant="outline" onPress={() => updateSecondColTo('广东')} fullWidth testID="btn-update-col2-gd" />
                            <UI.Button title="更新二列：浙江" variant="outline" onPress={() => updateSecondColTo('浙江')} fullWidth testID="btn-update-col2-zj" />
                            <UI.Button title="更新二列：四川" variant="outline" onPress={() => updateSecondColTo('四川')} fullWidth testID="btn-update-col2-sc" />
                        </View>
                    )}
                    {useMultiCols && (
                        <View style={[styles.row, { marginTop: 12 }]}>
                            <UI.Button title="选中：浙江, 宁波" variant="outline" onPress={() => setSelectionProvinceCity('浙江', 'nb')} fullWidth testID="btn-set-selection-zj-nb" />
                            <UI.Button title="选中：广东, 深圳" variant="outline" onPress={() => setSelectionProvinceCity('广东', 'sz')} fullWidth testID="btn-set-selection-gd-sz" />
                        </View>
                    )}

                    {/* 三列联动：更新日数 & 按值设置选中 */}
                    {useThreeCols && (
                        <View style={[styles.row, { marginTop: 12 }]}>
                            <UI.Button title="更新日列：28天" variant="outline" onPress={() => updateDaysTo(28)} fullWidth testID="btn-update-days-28" />
                            <UI.Button title="更新日列：30天" variant="outline" onPress={() => updateDaysTo(30)} fullWidth testID="btn-update-days-30" />
                            <UI.Button title="更新日列：31天" variant="outline" onPress={() => updateDaysTo(31)} fullWidth testID="btn-update-days-31" />
                        </View>
                    )}
                    {useThreeCols && (
                        <View style={[styles.row, { marginTop: 12 }]}>
                            <UI.Button title="选中：2025/6/30" variant="outline" onPress={() => setSelectionYMD(2025, 6, 30)} fullWidth testID="btn-set-selection-ymd-2025-6-30" />
                        </View>
                    )}

                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>提示：</UI.Text>
                        <UI.Text variant="body2" color="subtext">
                            受控用法可通过 updateColumns 动态更新列；通过 updateSelection 设置选中索引。点击“确定/取消”分别 resolve/reject。
                        </UI.Text>
                        <UI.Text variant="body2" color="subtext">
                            当前受控状态：{ctrlId ? `已打开（id=${ctrlId}）` : '未打开'}
                        </UI.Text>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default PickerTestScreen;